package com.xunwulian.base.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/26.
 */
public class BeanUtil3 {
    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    public <T> T jsonToBean(String json, Class<T> type) {
        return (T) gson.fromJson(json, type);
    }

    public <T> String beanToJson(T bean) {
        return gson.toJson(bean);
    }

    public <T> List<T> jsonToList(String json, Class<T> type) {
        List<T> beans = gson.fromJson(json, new TypeToken<List<T>>() {
        }.getType());
        List<T> beans2 = new ArrayList();
        for (T bean : beans) {
            String json2 = beanToJson(bean);
            T bean2 = jsonToBean(json2, type);
            beans2.add(bean2);
        }

        return beans2;
    }

    public <T> String listToJson(List<T> beans) {
        return gson.toJson(beans);
    }

    public <T> void log(T bean) {
        System.out.println(gson.toJson(bean));
    }

    public <T> void log(List<T> beans) {
        System.out.println(gson.toJson(beans));
    }
}
